<script setup lang="ts">
import { ref } from 'vue';
import type { UploadFileInfo } from 'naive-ui';
import { $t } from '@/locales';
import { useUpload } from '@/components/custom/upload-file/src/useUpload';

defineOptions({
  name: 'FileOperateModel'
});

const visible = defineModel<boolean>('visible', {
  default: false
});

const title = $t('page.base.file.list.uoloadFile');

function closeDrawer() {
  visible.value = false;
}

interface Emits {
  (e: 'submitted'): void;
}

const emit = defineEmits<Emits>();

const formLoading = ref(false); // 表单加载中

const { uploadUrl, httpRequest } = useUpload();

/** 文件上传之前校验 */
// const beforeUpload = (img: { file: UploadFileInfo; fileList: UploadFileInfo[] }) => {
//   if (
//     !img.file.file?.name.includes('.png') &&
//     !img.file.file?.name.includes('.jpg') &&
//     !img.file.file?.name.includes('.gif')
//   ) {
//     window.$message?.warning($t('common.allowFileImg'));
//     formLoading.value = false;
//     return false;
//   }
//   return true;
// };

/** 上传错误提示 */
const handleError = (): void => {
  window.$message?.error($t('common.uploadFileFailure'));
  formLoading.value = false;
};

/** 文件上传成功处理 */
const handleSuccess = ({ file }: { file: UploadFileInfo; event?: ProgressEvent }) => {
  file.percentage = 100;
  file.status = 'uploading';
  // 清理
  formLoading.value = false;
  // 提示成功，并刷新
  window.$message?.success($t('common.uploadFileSuccess'));
};

async function handleSubmit() {
  closeDrawer();
  emit('submitted');
}
</script>

<template>
  <NModal v-model:show="visible" :title="title" preset="card" class="w-150">
    <NUpload
      :action="uploadUrl"
      :max="1"
      :disabled="formLoading"
      :custom-request="httpRequest"
      @error="handleError"
      @finish="handleSuccess"
    >
      <NUploadDragger class="h-50">
        <div>
          <icon-ep:upload-filled class="text-16 color-gray-400" />
        </div>
        <NText>{{ $t('common.dragFileHere') }}</NText>
        <NText class="color-primary">{{ $t('common.clickUpload') }}</NText>
      </NUploadDragger>
    </NUpload>
    <template #footer>
      <NSpace justify="end" :size="16">
        <NButton :disabled="formLoading" @click="closeDrawer">{{ $t('common.cancel') }}</NButton>
        <NButton type="primary" :disabled="formLoading" @click="handleSubmit">{{ $t('common.confirm') }}</NButton>
      </NSpace>
    </template>
  </NModal>
</template>

<style scoped></style>
